#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

#include "protocol.h"

#ifdef USE_DOMAIN
#define SERVER "home.dybai.net"
#else
#define SERVER "10.200.0.2"
#endif // USE_DOMAIN

int main(int argc, char *argv[])
{
    int sockfd;
    struct sockaddr_in remoteAddr;
    char buf[BUFSIZ] = "";

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket()");
        exit(1);
    }

#ifdef USE_DOMAIN
    struct hostent *phostent = gethostbyname(SERVER);
    // int i;
    // for (i = 0; phostent->h_addr_list[i]; i++)
    // {
    //     printf("%s => %s\n", SERVER, phostent->h_addr_list[i]);
    // }
    uint32_t addr = 0;
    memcpy(&addr, phostent->h_addr_list[0], sizeof(uint32_t));
    printf("addr = %X\n", addr);
    // return 0;
#else
    uint32_t addr = inet_addr(SERVER);
    printf("addr=%d\n", addr);
#endif

    remoteAddr.sin_family = AF_INET;
    remoteAddr.sin_port = ntohs(PORT);
    // inet_aton("0.0.0.0", &remoteAddr.sin_addr);
    remoteAddr.sin_addr.s_addr = addr;
    printf("Connect to %s:%d\n", inet_ntoa(remoteAddr.sin_addr), ntohs(remoteAddr.sin_port));
    if (connect(sockfd, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr)))
    {
        perror("connect");
        goto CleanUp;
    }

    const char *msg = "My name is client!";
    if (send(sockfd, msg, strlen(msg), 0) < 0)
    {
        perror("send");
        goto CleanUp;
    }

    if (recv(sockfd, buf, BUFSIZ, 0) < 0)
    {
        perror("recv");
        goto CleanUp;
    }
    printf("From Server: %s\n", buf);

  CleanUp:
    close(sockfd);
    return 0;
}
